<template>
	<view class="bluetooth">
		<view class="blue-tooth-btn" v-if="!isSearching" @click="start()">开始搜索蓝牙</view>
		<view class="blue-tooth-btn" v-else @click="stopSearch()">停止搜索蓝牙</view>
		<!-- 蓝牙搜索loading -->
		<view class="loading" v-if="isSearching">
			<img src="/static/image/tools/loading.png" alt="" srcset="" />
			<text>蓝牙搜索中...</text>
		</view>
		<!-- 设备列表 -->
		<view class="device_list" v-if="!isSearching && devices.length > 0">
			<view class="device_item" v-for="(item, index) in devices" :key="item.deviceId"
				@click="handleDeviceSelect(item)">
				<text>{{item.name}}</text>
				<img src="/static/image/tools/arraw_r.png" alt="" />
			</view>
		</view>
		<!-- 选择跟踪的设备 -->
		<View class="choose-device" v-if="trackedDevice">
			<text class="device-name">{{trackedDevice.name}} —— {{trackedDevice.deviceId}}</text>    
			<view class="line">
				跟踪进度: {{getSignalStrength(trackedDevice.rssi)}} / 100
			</view>
			<Text class="direction-guide">
				{{getDirectionGuide(trackedDevice.rssi)}}
			</Text>
			        
		</View>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isSearching: false,
				devices: [],
				trackedDevice: null,
				// devices: [{
				// 	name: "未知设备01",
				// 	deviceId: 'DFGDGG3434fdfdsfds34432FDSFDF43',
				// 	rssi: -40,
				// }, {
				// 	name: "未知设备02",
				// 	deviceId: 'HJKBKJK678786BKBJKBJKB',
				// 	rssi: -50,
				// }],
				// trackedDevice: {
				// 	name: "未知设备01",
				// 	deviceId: 'DFGDGG3434fdfdsfds34432FDSFDF43',
				// 	rssi: -40,
				// }, 
				isBlueToothAvailable: false, // 蓝牙设备是否可用
			}
		},
		methods: {
			start() {
				this.isSearching = true;
				this.startSearch()
			},
			getDevices(newDevices, prevDevices) {
				const updatedDevices = [...prevDevices];
				newDevices.forEach((newDevice) => {
					const index = updatedDevices.findIndex(
						(d) => d.deviceId === newDevice.deviceId
					);
					if (index !== -1) {
						updatedDevices[index] = newDevice;
					} else {
						updatedDevices.push(newDevice);
					}
				});
				return updatedDevices.sort((a, b) => b.rssi - a.rssi);
			},
			// 选择设备
			handleDeviceSelect(device) {
				this.trackedDevice = device;
				uni.showToast({
					title: `正在跟踪: ${device.name}`,
					icon: "success"
				});
			},
			getSignalStrength(rssi) {
				if (rssi >= -50) return 100;
				if (rssi <= -100) return 0;
				return Math.round(((rssi + 100) / 50) * 100);
			},
			getDirectionGuide(rssi) {
				if (rssi >= -50) return "非常接近！你已经找到了！";
				if (rssi >= -70) return "很近了，继续朝这个方向移动！";
				if (rssi >= -90) return "正确方向，但还需要继续寻找。";
				return "信号较弱，尝试改变方向。";
			},
			startDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					success: () => {
						uni.onBluetoothDeviceFound((res) => {
							console.log('获取设备信息 ======>', res)
							const newDevices = res.devices.map((device) => ({
								name: device.name || "未知设备",
								deviceId: device.deviceId,
								rssi: device.RSSI,
							}));
							// 重新搜索设备之后更新的设备信息
							this.devices = this.getDevices(newDevices, this.devices);
							this.isSearching = false;
							this.stopSearch()
						})
					},
					fail: (error) => {
						console.error("启动蓝牙设备搜索失败：", error);
						uni.showToast({
							title: '启动蓝牙设备搜索失败',
							icon: 'none'
						});
						this.isSearching = false;
						this.stopSearch()
					},
				})
			},
			startSearch() {
				this.isBlueToothAvailable = true;
				uni.openBluetoothAdapter({
					success: () => {
						this.startDiscovery()
					},
					fail: (error) => {
						if (error.errMsg.includes("already opened")) {
							uni.showToast({
								title: "蓝牙已经开启",
								icon: "none",
							});
							startDiscovery();
						} else {
							console.error("初始化蓝牙适配器失败：", error);
							uni.showToast({
								title: "蓝牙初始化失败，请检查蓝牙是否开启",
								icon: "none",
							});
							this.isSearching = false
							this.isBlueToothAvailable = false
							this.stopSearch()
						}
					},
				});
			},
			stopSearch() {
				if (this.isBlueToothAvailable) {
					uni.stopBluetoothDevicesDiscovery({
						complete: () => {
							uni.closeBluetoothAdapter({
								complete: () => {
									this.isBlueToothAvailable = false
								},
							});
						},
					});
				}
			}
		},
	}
</script>

<style lang="scss">
	.bluetooth {
		height: 100vh;
		background-color: #f8f8f8;

		.blue-tooth-btn {
			height: 80rpx;
			margin: 20rpx 80rpx;
			border-radius: 40rpx;
			line-height: 80rpx;
			text-align: center;
			font-size: 16px;
			background-color: #548bf6;
		}

		.loading {
			display: flex;
			flex-direction: column;
			align-items: center;

			img {
				width: 50px;
				height: 50px;
			}
		}

		.device_list {
			background-color: #fff;
			border: #eeeeee solid 2rpx;
			border-radius: 10rpx;
			height: auto;
			margin: 20rpx 40rpx;
			padding: 0 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			align-items: center;

			.device_item {
				position: relative;
				height: 100rpx;
				width: 100%;
				line-height: 100rpx;
				border-bottom: 2px solid #eeeeee;
				text-align: center;

				&:last-child {
					border-bottom: none;
				}

				img {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					right: 16rpx;
					top: 30rpx;
				}
			}
		}
		
		.choose-device{
			box-shadow: 0px 1px 5px 0px rbga(29, 30, 31, 0.1);
			margin: 20rpx 10rpx;
			padding: 20rpx 32rpx;
			background-color: #fff;
			border-radius: 8rpx;
			.device-name{
				height: 60rpx;
				line-height: 60rpx;
				color: #548bf6;
				font-size: 16px;
				font-weight: 500;
			}
			.line{
				margin-top: 8rpx;
				height: 40rpx;
				line-height: 40rpx;
				color: #000000;
				font-size: 14px;
				font-weight: 400;
			}
			.direction-guide{
				margin-top: 14rpx;
				height: 40rpx;
				line-height: 40rpx;
				color: #000000;
				font-size: 14px;
				font-weight: 400;
			}
		}
	}
</style>